package com.wenyu.wenyuyuedu.global;

import com.wenyu.wenyuyuedu.utils.LogUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import retrofit2.Retrofit;

/**
 * Created by lenovo on 2016/11/13.
 * Retrofit的单例类
 */

public class ApiWrapper {
    private
    Retrofit retrofit;

    private
    static ApiWrapper instance;

    private ApiWrapper() {
        retrofit = new Retrofit.Builder()
                .baseUrl(QBangApis.BaseAPI)
                .addConverterFactory(MyConverterFactory.create())
                .client(getClient())
                .build();
    }


    // 添加拦截器打印接口url
    public OkHttpClient getClient() {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
        httpClient.addInterceptor(new Interceptor() {
            @Override
            public Response intercept(Interceptor.Chain chain) throws IOException {
                Request original = chain.request();
                LogUtils.netUrl(original.url().toString());
                return chain.proceed(original);
            }
        });
        return httpClient.build();
    }

    public static ApiWrapper getInstance() {
        if (instance == null) {
            synchronized (ApiWrapper.class) {
                if (instance == null) {
                    instance = new ApiWrapper();
                }
            }
        }
        return instance;
    }


    public <T> T create(Class<T> services) {
        return retrofit.create(services);
    }
}
